/**
 * 全局透明材质修复工具
 * 专门处理页面刷新后材质绑定时的透明材质问题
 */

/**
 * 获取场景对象 - 支持多种获取方式
 * @returns {THREE.Scene|null} 场景对象或null
 */
function getSceneObject() {
    // 尝试多种方式获取场景对象
    let scene = window.scene;
    
    // 如果window.scene不存在，尝试从manager获取
    if (!scene && window.manager && window.manager.scene) {
        scene = window.manager.scene;
        console.log('🔍 从window.manager.scene获取场景对象');
    }
    
    // 尝试从sceneTreeManager获取
    if (!scene && window.sceneTreeManager && window.sceneTreeManager.scene) {
        scene = window.sceneTreeManager.scene;
        console.log('🔍 从window.sceneTreeManager.scene获取场景对象');
    }
    
    // 尝试从sceneTreeUI获取
    if (!scene && window.sceneTreeUI && window.sceneTreeUI.scene) {
        scene = window.sceneTreeUI.scene;
        console.log('🔍 从window.sceneTreeUI.scene获取场景对象');
    }
    
    // 尝试从sceneTreeUI.treeManager获取
    if (!scene && window.sceneTreeUI && window.sceneTreeUI.treeManager && window.sceneTreeUI.treeManager.scene) {
        scene = window.sceneTreeUI.treeManager.scene;
        console.log('🔍 从window.sceneTreeUI.treeManager.scene获取场景对象');
    }
    
    return scene;
}

/**
 * 全局透明材质修复函数 - Alpha优先策略
 * 用于页面刷新后手动或自动修复所有透明材质
 */
function fixAllTransparentMaterials() {
    console.log('🔧 [全局透明修复] 开始修复场景中的所有透明材质...');
    
    const scene = getSceneObject();
    if (!scene) {
        console.error('❌ 无法获取场景对象');
        console.warn('💡 建议稍后手动执行 fixAllTransparentMaterials() 或等待自动重试');
        return 0;
    }
    
    console.log('✅ 成功获取场景对象，开始修复透明材质...');

    let fixedCount = 0;
    let totalMaterials = 0;

    scene.traverse((object) => {
        if (object.isMesh && object.material) {
            const materials = Array.isArray(object.material) ? object.material : [object.material];
            
            materials.forEach((material) => {
                totalMaterials++;
                
                // 🎯 Alpha优先策略：检查是否为透明材质
                const hasAlphaTransparency = material.transparent || 
                                           material.alphaTest > 0 || 
                                           material.opacity < 1 || 
                                           !!material.alphaMap;
                
                if (hasAlphaTransparency) {
                    const materialName = material.userData?.materialName || material.name || `Material_${totalMaterials}`;
                    // console.log(`🔧 [全局修复] 透明材质: ${object.name} - ${materialName}`);
                    // console.log(`   修复前: RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)}), opacity=${material.opacity}, alphaTest=${material.alphaTest}`);
                    
                    // 🔑 关键策略：alpha值为透明时，基础颜色设为白色，让alpha通道主导
                    const hasAlpha = material.opacity < 1 || material.alphaTest > 0 || !!material.alphaMap;
                    
                    if (hasAlpha) {
                        // 有alpha设置时，基础颜色设为白色，不干扰alpha效果
                        material.color.setRGB(1.0, 1.0, 1.0);
                        // 🔧 关键修复：强制触发材质更新，确保颜色变化立即生效
                        material.needsUpdate = true;
                        // console.log(`   🎨 Alpha优先策略：基础颜色设为白色，强制更新材质`);
                    }
                    
                    // 🎯 根据透明类型设置正确的参数
                    const matName = materialName.toLowerCase();
                    const meshName = (object.name || '').toLowerCase();
                    const isRoadLine = matName.includes('马路') || matName.includes('线') || 
                                     meshName.includes('马路') || meshName.includes('线') ||
                                     matName.includes('road') || matName.includes('line');
                    
                    if (material.opacity < 1) {
                        // opacity透明模式：以opacity值为准
                        material.transparent = true;
                        material.alphaTest = 0;
                        material.depthWrite = false;
                        material.depthTest = true;
                        object.renderOrder = isRoadLine ? 100 : 999;
                        // console.log(`   🔧 opacity透明模式：opacity=${material.opacity}, renderOrder=${object.renderOrder}`);
                        
                    } else if (material.alphaTest > 0 || material.alphaMap) {
                        // alphaTest透明模式：硬边透明
                        if (isRoadLine) {
                            material.transparent = false;
                            material.alphaTest = Math.max(0.1, material.alphaTest || 0.5);
                            material.depthWrite = true;
                            material.depthTest = true;
                            object.renderOrder = 100;
                            // console.log(`   🛣️ 马路线alphaTest模式：alphaTest=${material.alphaTest}`);
                        } else {
                            material.transparent = false;
                            material.alphaTest = material.alphaTest || 0.5;
                            material.depthWrite = true;
                            material.depthTest = true;
                            object.renderOrder = 200;
                            // console.log(`   🔧 alphaTest透明模式：alphaTest=${material.alphaTest}`);
                        }
                        
                    } else if (material.transparent) {
                        // 纯transparent模式
                        material.alphaTest = 0;
                        material.depthWrite = false;
                        material.depthTest = true;
                        object.renderOrder = 999;
                        // console.log(`   🔧 transparent模式：基础颜色白色化`);
                    }
                    
                    material.needsUpdate = true;
                    fixedCount++;
                    
                    // console.log(`   ✅ Alpha优先修复完成: RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)})`);
                    // console.log(`   💡 原理：alpha值主导透明效果，基础颜色和贴图RGB影响降低`);
                }
            });
        }
    });

    console.log(`🎨 [全局透明修复] 完成！总材质${totalMaterials}个，修复透明材质${fixedCount}个`);
    
    // 触发渲染更新
    if (window.manager && window.manager.render) {
        window.manager.render();
    }
    
    return fixedCount;
}

/**
 * 检查场景中的透明材质状态
 */
function checkTransparentMaterials() {
    console.log('🔍 [透明材质检查] 开始检查场景中的透明材质状态...');
    
    const scene = getSceneObject();
    if (!scene) {
        console.error('❌ 无法获取场景对象');
        console.warn('💡 建议稍后手动执行 checkTransparentMaterials() 或等待自动重试');
        return;
    }
    
    console.log('✅ 成功获取场景对象，开始检查透明材质...');

    const results = {
        total: 0,
        transparent: 0,
        needsFix: 0,
        details: []
    };

    scene.traverse((object) => {
        if (object.isMesh && object.material) {
            const materials = Array.isArray(object.material) ? object.material : [object.material];
            
            materials.forEach((material) => {
                results.total++;
                
                const hasAlphaTransparency = material.transparent || 
                                           material.alphaTest > 0 || 
                                           material.opacity < 1 || 
                                           !!material.alphaMap;
                
                if (hasAlphaTransparency) {
                    results.transparent++;
                    
                    const materialName = material.userData?.materialName || material.name || `Material_${results.total}`;
                    const hasAlpha = material.opacity < 1 || material.alphaTest > 0 || !!material.alphaMap;
                    const isWhiteBase = material.color.r >= 0.9 && material.color.g >= 0.9 && material.color.b >= 0.9;
                    
                    const needsFix = hasAlpha && !isWhiteBase;
                    if (needsFix) {
                        results.needsFix++;
                    }
                    
                    const detail = {
                        objectName: object.name,
                        materialName,
                        color: `RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)})`,
                        opacity: material.opacity,
                        alphaTest: material.alphaTest,
                        transparent: material.transparent,
                        hasAlphaMap: !!material.alphaMap,
                        needsFix,
                        status: needsFix ? '❌ 需要修复' : '✅ 正常'
                    };
                    
                    results.details.push(detail);
                    // console.log(`🔍 ${detail.objectName} - ${detail.materialName}: ${detail.status}`);
                    // console.log(`   颜色: ${detail.color}, opacity: ${detail.opacity}, alphaTest: ${detail.alphaTest}`);
                }
            });
        }
    });

    console.log(`📊 [检查结果] 总材质: ${results.total}, 透明材质: ${results.transparent}, 需要修复: ${results.needsFix}`);
    
    if (results.needsFix > 0) {
        console.log(`⚠️ 发现 ${results.needsFix} 个透明材质需要修复，建议运行 fixAllTransparentMaterials()`);
    } else {
        console.log(`✅ 所有透明材质状态正常`);
    }
    
    return results;
}

/**
 * 自动检测并修复透明材质（延迟执行，确保场景加载完成）
 */
function autoFixTransparentMaterialsDelayed(delay = 2000) {
    // console.log(`⏰ [自动修复] 将在 ${delay}ms 后自动检查并修复透明材质...`);
    
    setTimeout(() => {
        const checkResult = checkTransparentMaterials();
        
        if (checkResult && checkResult.needsFix > 0) {
            console.log(`🔧 [自动修复] 发现 ${checkResult.needsFix} 个透明材质需要修复，开始自动修复...`);
            fixAllTransparentMaterials();
        } else {
            console.log(`✅ [自动修复] 所有透明材质状态正常，无需修复`);
        }
    }, delay);
}

// 暴露到全局
window.fixAllTransparentMaterials = fixAllTransparentMaterials;
window.checkTransparentMaterials = checkTransparentMaterials;
window.autoFixTransparentMaterialsDelayed = autoFixTransparentMaterialsDelayed;

// 页面加载完成后自动检查（延迟执行）
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        autoFixTransparentMaterialsDelayed(3000);
    });
} else {
    autoFixTransparentMaterialsDelayed(3000);
}

// console.log('🔧 全局透明材质修复工具已加载');
// console.log('   使用方法:');
// console.log('   - fixAllTransparentMaterials()     // 修复所有透明材质');
// console.log('   - checkTransparentMaterials()      // 检查透明材质状态');
// console.log('   - autoFixTransparentMaterialsDelayed(delay) // 延迟自动修复');
